#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

# use physical pin numbers
GPIO.setmode(GPIO.BOARD)

# switch off GPIO warnings
GPIO.setwarnings(False)

output_pin = [3,5,7,8,10,11,12,13,15,16,18,19,21,22,23,24]
input_pin = 26

def init():
  # setup output pins, switch pins off
  for i in output_pin:
    GPIO.setup(i,GPIO.OUT,initial=0)
  # setup input pin; enable internal pull down resistor
  GPIO.setup(input_pin,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
  
def description():
  print ('7-Segment Display pidget methods:')
  print ('  init():                          initializes input and output pins')
  print ('  set_display(number):             sets Display to given number')
  print ('  set_digit(digit,number):         sets digit to given number')
  print ('  set_double_digit(double,number): sets two digits to number')
  print ('  get_switch():                    returns state of switch')

def set_digit(digit,number):  
  try:
    number=int(number)
    digit=int(digit)
    if (digit<0 or digit>3):
      print ('digit not in range [0,3]')
    else:
      if (number>9 or number<0):
        # set digit blank
        number=10
      for i in range (0,4):
        GPIO.output(output_pin[i+4*digit],(number & (1 << i)))
  except ValueError:
    print ('Error: digit/number is not an integer')

def set_display(number):
  try:
    number=int(number)
    if (number<0 or number>9999):
      print ('number not in range [0,9999]')
    else:
      for i in range (0,4):
        set_digit(i,int((number/10**i)%10))
  except ValueError:
    print ('Error: number is not an integer')

def set_double_digit(double,number):  
  try:
    number=int(number)
    double=int(double)
    if (number<0 or number>99):
      print ('number not in range [0,99]')
    elif (double<0 or double>1):
      print ('double not in range [0,1]')
    else:
      for i in range (0,2):
        set_digit(i+double*2,int((number/10**i)%10))
  except ValueError:
    print ('Error: double/number is not an integer')
    
def test():
  number = 1111
  for i in range (0,10):
    set_display(i*number)
    time.sleep(0.5)
  set_display(0)
  
def get_switch():
  return GPIO.input(26)
